﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Central_Control.Key;
using System.Net.Sockets;
using System.Net;
using Central_Control.展厅;
namespace Central_Control
{

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        UserControlGallery _userControlGallery;

        public ObservableCollection<GalleryButtonInfo> _Buttons;
        public ObservableCollection<GalleryButtonInfo> Buttons 
        {
            get { return _Buttons; }

            set{ _Buttons = value;OnPropertyChanged(nameof(Buttons)); }
        }

        private Visibility isCloseButtonVisible;
        public Visibility IsCloseButtonVisible
        {
            get { return isCloseButtonVisible; }
            set
            {
                if (isCloseButtonVisible != value)
                {
                    isCloseButtonVisible = value;
                    OnPropertyChanged(nameof(IsCloseButtonVisible));
                }
            }
        }
        public static MainWindow instance { get; private set; }

        string localAppDataDirectory;
        string jsonFilePath;
        public MainWindow()
        {
            InitializeComponent();
            Init();
        }

        void Init()
        {
            this.DataContext = this;
            instance = this;
            IsCloseButtonVisible = Visibility.Hidden;
            localAppDataDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Central Control");
            jsonFilePath = System.IO.Path.Combine(localAppDataDirectory, "GalleryInfoJson.json");
            LoadGalleryButtonInfoFromJson(); // 加载按钮信息
                                             //UpdateButtonWrapPanel(); // 更新按钮列表
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public void RefreshUIFromJson()
        {
            // 重新加载按钮信息
            LoadGalleryButtonInfoFromJson();

        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.DataContext is GalleryButtonInfo gallerybuttonInfos)
            {
                // 弹出对话框，让用户输入要删除的按钮名称
               MessageBoxResult result=  MessageBox.Show($"要删除{gallerybuttonInfos.Name}吗?", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    GalleryButtonInfo targetButton = Buttons.FirstOrDefault(button => button.ID == gallerybuttonInfos.ID);
                    if (targetButton != null)
                    {
                        Buttons.Remove(targetButton);
                    }
                    SaveGalleryButtonInfoToJson();
                    RefreshUIFromJson();
                }
            }

        }

        //右上角设置按钮，打开管理员登录页面
        private void login_Click(object sender, RoutedEventArgs e)
        {
            LoginWindow loginWindow = new LoginWindow();
            loginWindow.Owner = this; // 设置新窗口的Owner为当前窗口
            loginWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; // 设置新窗口在Owner窗口中间打开
            loginWindow.ShowDialog();
        }

        public void AddButton(string name)
        {
            // 检查按钮名称是否已存在
            if (Buttons.Any(button => button.Name == name))
            {
                MessageBox.Show("展厅已存在");
                return; // 不添加重复的按钮
            }
            if (Buttons != null && Buttons.Count > 0)
            {
                Buttons.Add(new GalleryButtonInfo
                {
                    Name = name,
                    ID = Buttons.Last().ID + 1
                });
            }
            else
            {
                Buttons.Add(new GalleryButtonInfo
                {
                    Name = name,
                    ID =1
                });
            }

            // 保存按钮信息到JSON文件
            SaveGalleryButtonInfoToJson();
        }

        public bool DeleteButton(string name)
        {
            var buttonToDelete = Buttons.FirstOrDefault(btn => btn.Name == name);
            if (buttonToDelete != null)
            {
                Buttons.Remove(buttonToDelete);
                // 保存按钮信息到JSON文件
                SaveGalleryButtonInfoToJson();
                return true; // 返回删除成功
            }

            return false; // 返回删除失败，按钮不存在
        }

        // 保存按钮信息到JSON文件的方法
        public void SaveGalleryButtonInfoToJson()
        {
            // 将Buttons集合序列化为JSON并保存到文件
            string json = JsonConvert.SerializeObject(Buttons);
            File.WriteAllText(jsonFilePath, json);
        }

        private void LoadGalleryButtonInfoFromJson()
        {
            try
            {
                string json = File.ReadAllText(jsonFilePath);
                Buttons = JsonConvert.DeserializeObject<ObservableCollection<GalleryButtonInfo>>(json);
            }
            catch (FileNotFoundException)
            {
                Buttons = new ObservableCollection<GalleryButtonInfo>();
            }
            catch (JsonException)
            {
                Buttons = new ObservableCollection<GalleryButtonInfo>();
            }
        }


        //关闭首页后结束整个程序程序进程
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            Application.Current.Shutdown();
        }


        //保证程序运行就在屏幕中央
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 计算窗口在屏幕中心的位置
            //double screenWidth = SystemParameters.PrimaryScreenWidth;
            //double screenHeight = SystemParameters.PrimaryScreenHeight;
            //double windowWidth = this.Width;
            //double windowHeight = this.Height;

            //this.Left = (screenWidth - windowWidth) / 2;
            //this.Top = (screenHeight - windowHeight) / 2;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 处理按钮点击事件
            Button button = (Button)sender;
            string buttonName = button.Content.ToString();
            MessageBox.Show($"Button {buttonName} clicked!");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (sender is Button button&& button.DataContext is GalleryButtonInfo gallerybuttonInfos)
            {
                //OpenGalleryWindow(gallerybuttonInfos);
                if (_userControlGallery == null)
                {
                    _userControlGallery = new UserControlGallery(mainFrame, gallerybuttonInfos);
                    mainFrame.Navigate(_userControlGallery);
                }
                else
                {
                    mainFrame.Visibility = Visibility.Visible;
                    _userControlGallery.galleryButtonInfo = gallerybuttonInfos;
                    _userControlGallery.Init();
                }
                //mainFrame.Navigate(new UserControlGallery(mainFrame));
                if (gallerybuttonInfos.Name=="网络唤醒") 
                {
                    WakeUp();
                    MessageBox.Show("唤醒计算机");
                }
                else 
                { 
                   // MessageBox.Show(gallerybuttonInfos.Name+"-->ID:"+ gallerybuttonInfos.ID.ToString());
                }
            }
        }

        private void OpenGalleryWindow(GalleryButtonInfo galleryButtonInfo)
        {
            //Window1 window1 = new Window1();


            Gallery gallery = new Gallery();
            gallery.galleryButtonInfo = galleryButtonInfo;
            this.Visibility = Visibility.Collapsed;
            gallery.Owner = this; // 设置新窗口的Owner为当前窗口
            gallery.WindowStartupLocation = WindowStartupLocation.CenterOwner; // 设置新窗口在Owner窗口中间打开
            gallery.ShowDialog();

            //window1.Owner = this; // 设置新窗口的Owner为当前窗口
            //window1.WindowStartupLocation = WindowStartupLocation.CenterOwner; // 设置新窗口在Owner窗口中间打开
            //window1.ShowDialog();
        }

        public static void WakeUp()
        {
            // 硬编码的MAC地址
            string macAddress = "20-23-4C-88-85-C2"; // 替换为目标计算机的MAC地址

            byte[] macBytes = GetMacBytes(macAddress);
            byte[] packet = new byte[17 * 6];

            // 构造魔术包
            for (int i = 0; i < 6; i++)
            {
                packet[i] = 0xFF;
            }
            for (int i = 1; i <= 16; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    packet[i * 6 + j] = macBytes[j];
                }
            }

            // 发送魔术包
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 4000);
            client.Send(packet, packet.Length);
            client.Close();
        }

        private static byte[] GetMacBytes(string macAddress)
        {
            byte[] bytes = new byte[6];
            string[] hex = macAddress.Split('-');
            if (hex.Length != 6)
            {
                throw new ArgumentException("Invalid MAC address.");
            }
            try
            {
                for (int i = 0; i < 6; i++)
                {
                    bytes[i] = Convert.ToByte(hex[i], 16);
                }
            }
            catch (FormatException)
            {
                throw new ArgumentException("Invalid MAC address.");
            }
            return bytes;
        }

        public void CreatGalleryInfoJson()
        {
            // 创建包含指定内容的 JSON 对象
            GalleryButtonInfo jsonObject = new GalleryButtonInfo
            {
                ID = 0,
                Name = null,
                pcInfos=null
            };
            // 将 JSON 对象序列化为 JSON 字符串
            string jsonString = JsonConvert.SerializeObject(jsonObject);

            // 将 JSON 字符串写入文件
            File.WriteAllText(jsonFilePath, jsonString);
        }
    }




    //首页展厅按钮信息
    public class GalleryButtonInfo 
    {
        public int ID;
        public string Name { get; set; }
        public List<PcInfo> pcInfos;
        public List<PcInfo> AddPcInfos;
    }

    public class PcInfo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string IP { get; set; }
        public int Port { get; set; }
        public string MAC { get; set; }
        public bool isAdd { get; set; }
    }
}
